package com.ray.friendslist;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.ray.friendslist.adaptor.FriendsCursorAdapter;
import com.ray.friendslist.api.PostRequest;
import com.ray.friendslist.content.contract.FriendsContract;
import com.ray.friendslist.content.task.ParamCallback;
import com.ray.friendslist.service.VKFriendsService;
import com.ray.friendslist.token.VkTokenManager;

public class VkFriendsListActivity extends FragmentActivity implements
		LoaderCallbacks<Cursor>, OnItemClickListener {

	private static final String USER_ID = "USER_ID";

	private ListView mListView;

	private ProgressBar mProgressBar;

	private FriendsCursorAdapter mCursorAdapter;

	private BroadcastReceiver mBroadcastReceiver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_friends_list);
		Log.i("ray", "Access token = " + VkTokenManager.getTooken());
		mProgressBar = (ProgressBar) findViewById(android.R.id.progress);
		mProgressBar.setVisibility(ProgressBar.VISIBLE);
		mListView = (ListView) findViewById(android.R.id.list);
		mBroadcastReceiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {

				String action = intent.getAction();
				if (action.equals(VKFriendsService.ACTION_ON_ERROR)) {
					mProgressBar.setVisibility(View.INVISIBLE);
					Toast.makeText(
							VkFriendsListActivity.this,
							intent.getStringExtra(VKFriendsService.EXTRA_KEY_MESSAGE),
							Toast.LENGTH_SHORT).show();
				} else if (action.equals(VKFriendsService.ACTION_ON_SUCCESS)) {
					mProgressBar.setVisibility(View.INVISIBLE);
				}
			}
		};
		IntentFilter filter = new IntentFilter();
		filter.addAction(VKFriendsService.ACTION_ON_ERROR);
		filter.addAction(VKFriendsService.ACTION_ON_SUCCESS);
		registerReceiver(mBroadcastReceiver, filter);
		mCursorAdapter = new FriendsCursorAdapter(this, null);
		mListView.setAdapter(mCursorAdapter);
		mListView.setOnItemClickListener(this);
		getSupportLoaderManager().initLoader(0, null, this);
		mProgressBar.setVisibility(ProgressBar.GONE);
	}

	public void onVkRefreshButtonClick(View view) {
		mProgressBar = (ProgressBar) findViewById(android.R.id.progress);
		mProgressBar.setVisibility(ProgressBar.VISIBLE);
		Intent intent = new Intent(this, VKFriendsService.class);
		startService(intent);
	}

	public void onFeedActivityStart(View view) {
		startActivity(new Intent(this, VKFeedActivity.class));
	}

	@Override
	protected void onResume() {
		super.onResume();
		mCursorAdapter.notifyDataSetChanged();
	}

	public void postOnWallClick(View view) throws ClientProtocolException,
			IOException {
		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("message", "fuckIT!"));
		new PostRequest(new ParamCallback<String>() {

			public void onSuccess(String c) {
				Toast.makeText(VkFriendsListActivity.this, "Posted",
						Toast.LENGTH_LONG).show();
				NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
						VkFriendsListActivity.this)
						.setSmallIcon(android.R.drawable.ic_menu_send)
						.setContentTitle("FriendsList")
						.setContentText("Your Message Posted");
				NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
				String[] events = new String[6];
				// Sets a title for the Inbox style big view
				inboxStyle.setBigContentTitle("Event tracker details:");
				for (int i = 0; i < events.length; i++) {
					events[i] = "event " + i;
				}
				// Moves events into the big view
				for (int i = 0; i < events.length; i++) {
					inboxStyle.addLine(events[i]);
				}
				// Moves the big view style object into the notification object.
				mBuilder.setStyle(inboxStyle);
				// Creates an explicit intent for an Activity in your app
				Intent resultIntent = new Intent(VkFriendsListActivity.this,
						VkFriendsListActivity.class);

				// The stack builder object will contain an artificial back
				// stack for the
				// started Activity.
				// This ensures that navigating backward from the Activity leads
				// out of
				// your application to the Home screen.
				TaskStackBuilder stackBuilder = TaskStackBuilder
						.create(VkFriendsListActivity.this);
				// Adds the back stack for the Intent (but not the Intent
				// itself)
				stackBuilder.addParentStack(VkFriendsListActivity.class);
				// Adds the Intent that starts the Activity to the top of the
				// stack
				stackBuilder.addNextIntent(resultIntent);
				PendingIntent resultPendingIntent = stackBuilder
						.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
				mBuilder.setContentIntent(resultPendingIntent);
				NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
				// mId allows you to update the notification later on.
				mNotificationManager.notify(1, mBuilder.build());
			}

			public void onError(Throwable e) {
				Toast.makeText(VkFriendsListActivity.this,
						"Exception: " + e.getMessage(), Toast.LENGTH_LONG)
						.show();
				Log.e("ray", e.getMessage());
			}
		}, "wall.post", params).start("");
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mBroadcastReceiver);
	}

	public Loader<Cursor> onCreateLoader(int paramInt, Bundle paramBundle) {
		return new CursorLoader(this,
				FriendsContract.FriendsColumns.CONTENT_URI, null,null, null,
				null);
	}

	public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
		mCursorAdapter.swapCursor(arg1);
	}

	public void onLoaderReset(Loader<Cursor> paramLoader) {
		mCursorAdapter.swapCursor(null);
	}

	public void onItemClick(AdapterView<?> adapterView, View view,
			int position, long arg3) {
		Cursor cursor = (Cursor) adapterView.getItemAtPosition(position);
		Intent intent = new Intent(this, VkUserProfileActivity.class);
		intent.putExtra(USER_ID, cursor.getString(cursor.getColumnIndex(FriendsContract.FriendsColumns.VK_FRIEND_ID)));
		startActivity(intent);
	}
}